<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>验证码</title>
  </head>
  <body>
    <div class="v_code">
      <div class="code-show">
        <span class="code" id="checkCode"></span>
        <a href="" id="linkbt">看不清换一张</a>
      </div>
      <div class="inputCode">
        <label for="inputCode">验证码:</label>
        <input type="text" id="inputCode" />
        <span id="text_show"></span>
      </div>
      <input type="button" id="Button1" value="确定" />
    </div>
    <script>
      //1 生成验证码
      // 6位数 0-9 a-f 随机生成6位，内部必须是0-9 a-f 字符串
      // 数组 下标 0、1、2......从数组当中 随机下标0-15位

      // 2 进行验证
      window.onload = function () {
        var res = getCode();
        function getCode() {
          var arr = [
            "0",
            "1",
            "2",
            "3",
            "4",
            "5",
            "6",
            "7",
            "8",
            "9",
            "a",
            "b",
            "c",
            "d",
            "e",
            "f",
          ];
          var str = "";
          for (var i = 0; i < 6; i++) {
            var num = Math.round(Math.random() * (15 - 0) + 0);
            str += arr[num];
          }
          return str;
        }
        document.getElementById("checkCode").innerText = res;
        // 点击看不清，换一张事件
        document.getElementById("linkbt").onclick = function () {
          document.getElementById("checkCode").innerText = res;
        }
      };
      // 提交进行对比
      document.getElementById('Button1').onclick=function(){
        var code = document.getElementById('checkCode').innerHTML;
        var inputValue = document.getElementById('inputCode').value;
        if(code!==inputValue){
          alert('您输入的验证码不正确');
          document.getElementById('inputCode').value='';
          return false
        }else{
          location.href=('https://www.runoob.com/jsref/jsref-random.html')
        }
      }
    </script>
  </body>
</html>
